package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.SA;
import cn.edu.sdjzu.xg.kcsj.security.User;
import cn.edu.sdjzu.xg.kcsj.service.SAService;
import cn.edu.sdjzu.xg.kcsj.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/findmyActivity")
public class StudentfindActivityController extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(SaAddController.class);
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//将request body转换为JSON字串
        String actor_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin =  JSON.parseObject(actor_json, User.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            // 如果为空直接往前台响应"未收到请求信息"
            if (actor_json == null) {
                message.put("message", "未收到请求信息");
                log.debug("未收到请求信息");
                // 勿忘在前台输出message
                response.getWriter().println(message);
            } else { // 请求不为空
                response.getWriter().println(userToLogin.toString());
                Collection<SA> sas = SAService.getInstance().getAllActivitiesOfStudent(userToLogin);
                response.getWriter().println(sas);
                response.getWriter().println(message);
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
